package com.cloudspace.jindun.activity.dianhua;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.error.VolleyError;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.CustomTitleBaseActivity;
import com.cloudspace.jindun.manager.ContactPersonManager;
import com.cloudspace.jindun.model.Person;
import com.cloudspace.jindun.model.RemarkResult;
import com.cloudspace.jindun.module.ActionItem;
import com.cloudspace.jindun.net.manager.ImageManager;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.CallingUtils;
import com.cloudspace.jindun.utils.MMAlert;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;

import io.rong.imkit.RongIM;

import static java.net.HttpURLConnection.HTTP_OK;


/**
 * Created by zengxianhua on 17/1/2.
 */

public class LinkmanActivity extends CustomTitleBaseActivity implements View.OnClickListener{
    private TextView name;
    private ImageView icon;
    private TextView company;
    private TextView department;
    private TextView message;

    private TextView phone;
    private Person person;
    private ImageView urgency;

    private View call;

    private View menus;
    private TextView menuRename;
    private TextView menuDel;

    private View.OnClickListener phoneClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!ObjUtil.isEmpty(person)){
                CallingUtils.showCallMethodDialog(LinkmanActivity.this, person);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_link_man_data);

        getTitleBar().setSimpleMode(getResources().getString(R.string.personalData), new ActionItem(R.drawable.linkmenu, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (menus.getVisibility() != View.VISIBLE) {
                    menus.setVisibility(View.VISIBLE);
                } else {
                    menus.setVisibility(View.GONE);
                }
            }
        }));

        initView();
        setListener();
        Intent intent = getIntent();
        if (intent != null) {
            person = (Person) intent.getSerializableExtra("person");
            setData();
        }


    }

    private void setListener() {
        message.setOnClickListener(this);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void setData() {

        if (ObjUtil.isEmpty(person)){
            return;
        }

        ImageManager.loadCircleImage(this, icon, person.getImageUrl());
        name.setText(person.getRemarkName());
        company.setText(person.getOrganName());
        department.setText(person.getDepartName());
        phone.setText(person.getPhoneNumber());
        phone.setOnClickListener(phoneClickListener);
        urgency.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchIsExi();
            }
        });

        isEmergencyContactPerson = "0001".equals(person.getIsExiPreLink());
        showUrgencySwitch();
    }

    private void showUrgencySwitch() {
        urgency.setImageResource(isEmergencyContactPerson ? R.drawable.switch_ : R.drawable.shut);
    }

    private boolean isEmergencyContactPerson = false;

    private void switchIsExi() {
        API.getInstance().getOrgApi().isExiPerson(TAG, UserSessionManager.getInstance().getUserId(), person.getUserId(), !isEmergencyContactPerson, new ApiCallback<RemarkResult>() {
            @Override
            public void handleResult(RemarkResult result, VolleyError error) {
                if (error == null && result != null && result.getStatus() == HTTP_OK){
                    isEmergencyContactPerson = !isEmergencyContactPerson;
                    showUrgencySwitch();
                }else{
                    ToastMaker.showToastShort(getResources().getString(R.string.op_error));
                }
            }
        });


    }

    private void initView() {
        name = (TextView) findViewById(R.id.phone_tv_name);
        icon = (ImageView) findViewById(R.id.phone_iv_head);
        company = (TextView) findViewById(R.id.phone_tv_companyName);
        department = (TextView) findViewById(R.id.phone_tv_department);
        urgency = (ImageView) findViewById(R.id.phone_sc_urgencyLinkman);
        phone = (TextView) findViewById(R.id.phone_tv_tele);

        message= (TextView) findViewById(R.id.phone_tv_sendMessage);

        phone.setOnClickListener(phoneClickListener);


        menus = findViewById(R.id.menuly);
        menus.setVisibility(View.GONE);

        menuRename = (TextView) findViewById(R.id.renameMenu);
        menuRename.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoRenameActivity();
            }
        });
        menuDel = (TextView) findViewById(R.id.delMenu);
        menuDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDelConfirmDialog();
            }
        });

        call = findViewById(R.id.phone_tv_call);
        call.setOnClickListener(phoneClickListener);
    }

    public static final int REQUEST_CODE = 101;

    private void gotoRenameActivity() {
        Intent intent = new Intent(this, RemarkManActivity.class);
        intent.putExtra("id", person.getUserId());
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK){
            String remark = data.getStringExtra("remark");
            if (!TextUtils.isEmpty(remark)){
                name.setText(remark);
            }
        }
    }

    private void showDelDialog() {
        MMAlert.showAlert(this, getResources().getString(R.string.linkman_del_info),
                getResources().getString(R.string.linkman_info),
                getResources().getString(R.string.linkman_ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteAFreind();
                    }
                });
    }

    private void deleteAFreind() {
        API.getInstance().getOrgApi().deleteFriend(TAG, UserSessionManager.getInstance().getUserId(), person.getUserId(), new ApiCallback<RemarkResult>() {
            @Override
            public void handleResult(RemarkResult result, VolleyError error) {
                if (error == null && result != null && result.getStatus() == HTTP_OK){
                    ContactPersonManager.getInstance().deleteContactPerson(person.getUserId());
                    finish();
                }else{
                    ToastMaker.showToastLong(getResources().getString(R.string.op_error));
                }
            }
        });
    }

    private void showDelConfirmDialog() {
        MMAlert.showAlert(this, getResources().getString(R.string.linkman_del_sure),
                getResources().getString(R.string.linkman_op),
                getResources().getString(R.string.linkman_del_ok),
                true,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showDelDialog();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.phone_tv_sendMessage:
                if (RongIM.getInstance() != null) {
                    RongIM.getInstance().startPrivateChat(this, person.getUserId(), person.getName() );
                }

                break;


        }
    }
}
